package cn.agiledata.bank.myspace.action;

import java.awt.Image;
import java.io.InputStream;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ocx.AESWithJCE;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import cn.agiledata.bank.account.dao.hibernate.HibernateAccountDAO;
import cn.agiledata.bank.account.service.AccountSummary;
import cn.agiledata.bank.account.service.DefaultUserSummary;
import cn.agiledata.bank.account.service.IAccountConst;
import cn.agiledata.bank.account.service.IAccountService;
import cn.agiledata.bank.account.service.IReturnCodeHolder;
import cn.agiledata.bank.common.dao.AccountTemplateInter;
import cn.agiledata.bank.common.dao.SysTemplate;
import cn.agiledata.bank.common.dao.TransactionListPage;
import cn.agiledata.bank.common.dao.TransactionTemplate;
import cn.agiledata.bank.common.exception.BusinessException;
import cn.agiledata.bank.common.service.ICommonService;
import cn.agiledata.bank.common.service.SysSet;
import cn.agiledata.bank.common.service.email.BankCardMail;
import cn.agiledata.bank.common.servlet.InitForString;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.ForeDict;
import cn.agiledata.bank.common.util.PageBean;
import cn.agiledata.bank.common.util.SecurityUtil;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.UniqueIdentityUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.common.util.WebUtil;
import cn.agiledata.bank.facade.ServiceFacade;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.AccountBank;
import cn.agiledata.bank.hibernateBean.AccountHis;
import cn.agiledata.bank.hibernateBean.BankInfo;
import cn.agiledata.bank.hibernateBean.CityInfo;
import cn.agiledata.bank.hibernateBean.GradeRules;
import cn.agiledata.bank.hibernateBean.Operator;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.hibernateBean.SysParameter;
import cn.agiledata.bank.login.form.ResetPwdForm;
import cn.agiledata.bank.myspace.bean.AuthenticationBean;
import cn.agiledata.bank.myspace.exception.MySpaceException;
import cn.agiledata.bank.myspace.form.AccountUserInfoForm;
import cn.agiledata.bank.myspace.form.IVRPassForm;
import cn.agiledata.bank.myspace.form.MailActionForm;
import cn.agiledata.bank.myspace.form.ModifyLoginPassForm;
import cn.agiledata.bank.myspace.form.MyAccountBankForm;
import cn.agiledata.bank.myspace.service.AuthenticateService;
import cn.agiledata.bank.myspace.service.IMySpaceService;
import cn.agiledata.bank.scores.service.IScoresService;
import cn.agiledata.bank.scores.service.ScoresFactory;

import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;
import com.vnv.infrastructure.logic.IPBMgrFactory;

public class AccountAction extends AbstractMySpaceAction {
	private ICommonService ics = (ICommonService) IPBAppFactory
			.getObj("commonServices");

	protected IMySpaceService getMySpaceService() throws IPBException {
		return (IMySpaceService) IPBAppFactory.getObj(IMySpaceService.MGR_ID);
	}

	private AuthenticateService getAuthenticateService() {
		return (AuthenticateService) IPBAppFactory
				.getObj("authenticateService");
	}

	//
	public ActionForward accountInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		Account account = getAccount(request);
		//
		request.getSession().removeAttribute("contextType");
		request.setAttribute("account", account);
		String idcardStatus = getAuthenticateService()
				.getIdcardAuthenticationStatus(account);
		request.setAttribute("idcardStatus", idcardStatus == null ? ""
				: idcardStatus);
		total(account, request);

		TransactionListPage pl = new TransactionListPage(0, account.getId()
				.longValue());

		PageBean pb = pl.getAccountListPageBean();
		request.setAttribute("waitTotal", String.valueOf(pb.getTotalCount()));

		return mapping.findForward("accountInfo");
	}

	// 查看个人信息
	public ActionForward accountUserInfo(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		Account account = getAccount(request);
		request.setAttribute("account", account);

		String idcardStatus = getAuthenticateService()
				.getIdcardAuthenticationStatus(account);
		request.setAttribute("idcardStatus", idcardStatus == null ? ""
				: idcardStatus);

		String hideIdCode = "";
		if (account.getIdCode() != null && !account.getIdCode().equals("")) {
			hideIdCode = StringUtil.hiddenStr(account.getIdCode());
		}
		request.setAttribute("hideIdCode", hideIdCode);

		Blob photoBack = account.getTempCardPhotoBack();
		if (photoBack != null && photoBack.length() > 1) {
			request.setAttribute("cardPhotoBack", "show");
		} else {
			request.setAttribute("cardPhotoBack", "");
		}
		return mapping.findForward("accountUserInfo");
	}

	public ActionForward corpAccountUserInfo(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		request.setAttribute("province", InitForString.dataDictMap
				.get("PROVINCE_INFO"));
		AccountUserInfoForm theform = (AccountUserInfoForm) form;
		Account account = getAccount(request);

		BeanUtils.copyProperties(theform, account);
		request.setAttribute("account", account);

		if (COMPANY_TYPE_GATEWAY.equals(account.getCompanyType())) {
			WebUtil.setSessionString(request, "modual", "custInfo");
		}
		return mapping.findForward("corpAccountUserInfo");
	}

	public ActionForward modifyCorpAccountUserInfo(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		request.setAttribute("province", InitForString.dataDictMap
				.get("PROVINCE_INFO"));
		AccountUserInfoForm theform = (AccountUserInfoForm) form;
		Account account = getAccount(request);

		BeanUtils.copyProperties(theform, account);
		request.setAttribute("account", account);

		// 网关帐户 用户资料修改 跳转控制
		if (COMPANY_TYPE_GATEWAY.equals(account.getCompanyType())) {
			WebUtil.setSessionString(request, "modual", "custInfo");
		}
		return mapping.findForward("modifyCorpAccountUserInfo");
	}

	public ActionForward modifyCorpAccountUserInfoSubmit(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		AccountUserInfoForm theform = (AccountUserInfoForm) form;

		Account account = getAccount(request);
		// 网关帐户 用户资料修改 跳转控制
		if (COMPANY_TYPE_GATEWAY.equals(account.getCompanyType())) {
			WebUtil.setSessionString(request, "modual", "custInfo");
		}

		account.getAccountCompany().setPrinName(
				request.getParameter("prinName") != null ? request
						.getParameter("prinName") : "");
		account.getAccountCompany().setPrinTel(
				request.getParameter("prinTel") != null ? request
						.getParameter("prinTel") : "");
		account.getAccountCompany().setLinkMan(
				request.getParameter("linkMan") != null ? request
						.getParameter("linkMan") : "");
		account.getAccountCompany().setLinkTel(
				request.getParameter("linkTel") != null ? request
						.getParameter("linkTel") : "");
		account.getAccountCompany().setRegiAddr(
				request.getParameter("regiAddr") != null ? request
						.getParameter("regiAddr") : "");
		account.getAccountCompany().setRegiZip(
				request.getParameter("regiZip") != null ? request
						.getParameter("regiZip") : "");

		account.setUpdateUser(getAccountId(request));
		account.setUpdateTime(new Date());

		InputStream photoStream = null;
		InputStream cardPhotoStream = null;
		if (theform.getTheFiles1() != null
				&& theform.getTheFiles1().getFileSize() != 0) {
			FormFile formFile = (FormFile) theform.getTheFiles1();
			if (formFile != null) {
				int fileSize = formFile.getFileSize();
				if (fileSize > Constant.FILESIZE_512K) {
					this.setReturnCode(request,
							IReturnCodeHolder.PHOTO_OVERFLOW, MODIFY_ACCOUNT);
					return mapping.findForward(FAILURE);
				} else {
					photoStream = formFile.getInputStream();
					Image src = ImageIO.read(photoStream);
					if (src == null) {
						this.setReturnCode(request,
								IReturnCodeHolder.PHOTO_FORMAT_ERROR,
								MODIFY_ACCOUNT);
						return mapping.findForward(FAILURE);
					}
					photoStream.close();
					photoStream = formFile.getInputStream();
				}
			}
		}

		getMySpaceService().saveOrUpdateAccount(account, photoStream,
				cardPhotoStream);

		return mapping.findForward("corpAccountUserInfo");
	}

	public ActionForward modifyAccountUserInfo(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		List provinceList = (List) InitForString.dataDictMap
				.get("PROVINCE_INFO");
		request.setAttribute("province", provinceList);

		AccountUserInfoForm theform = (AccountUserInfoForm) form;
		Account account = getAccount(request);
		List cityList = null;
		if (account.getProvSeq() != null) {
			cityList = (List) InitForString.dataDictMap.get(account
					.getProvSeq().toString());
		} else {
			cityList = (List) InitForString.dataDictMap
					.get(((CityInfo) provinceList.get(0)).getCityId());
		}
		// add by zln 20080730 修正，如果account city未找到响应对象，取得默认city list
		if (cityList == null) {
			cityList = (List) InitForString.dataDictMap
					.get(((CityInfo) provinceList.get(0)).getCityId());
		}

		request.setAttribute("city", cityList);

		if (!StringUtil.isStrEmpty(account.getName())) {
			theform.setName(account.getName());
		}

		BeanUtils.copyProperties(theform, account);

		request.setAttribute("account", account);

		String idcardStatus = getAuthenticateService()
				.getIdcardAuthenticationStatus(account);
		request.setAttribute("idcardStatus", idcardStatus == null ? ""
				: idcardStatus);

		return mapping.findForward("modifyAccountUserInfo");
	}

	public ActionForward modifyAccountUserInfoSubmit(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		AccountUserInfoForm theform = (AccountUserInfoForm) form;

		Account account = getAccount(request);
		if (!StringUtil.isStrEmpty(account.getName())) {
			theform.setName(account.getName());
		}
		BeanUtils.copyProperties(account, theform);
		if (!StringUtil.isStrEmpty(theform.getBday())) {
			account.setBirthday(DateUtil.string2Date(theform.getBday()));
		} else {
			account.setBirthday(null);
		}

		account.setUpdateUser(getAccountId(request));
		account.setUpdateTime(new Date());

		InputStream photoStream = null;
		InputStream cardPhotoStream = null;
		if (theform.getTheFiles1() != null
				&& theform.getTheFiles1().getFileSize() != 0) {
			FormFile formFile = (FormFile) theform.getTheFiles1();
			if (formFile != null) {
				int fileSize = formFile.getFileSize();
				if (fileSize > Constant.FILESIZE_512K) {
					this.setReturnCode(request,
							IReturnCodeHolder.PHOTO_OVERFLOW, MODIFY_ACCOUNT);
					return mapping.findForward(FAILURE);
				} else {
					photoStream = formFile.getInputStream();
					Image src = ImageIO.read(photoStream);
					if (src == null) {
						this.setReturnCode(request,
								IReturnCodeHolder.PHOTO_FORMAT_ERROR,
								MODIFY_ACCOUNT);
						return mapping.findForward(FAILURE);
					}
					photoStream.close();
					photoStream = formFile.getInputStream();
				}
			}
		}
		if (theform.getTheFiles2() != null
				&& theform.getTheFiles2().getFileSize() != 0) {
			FormFile formFile = (FormFile) theform.getTheFiles2();
			if (formFile != null) {
				int fileSize = formFile.getFileSize();
				if (fileSize > Constant.FILESIZE_512K) {
					this.setReturnCode(request,
							IReturnCodeHolder.CARDPHOTO_OVERFLOW,
							MODIFY_ACCOUNT);
					return mapping.findForward(FAILURE);
				} else {
					cardPhotoStream = formFile.getInputStream();
					Image src = ImageIO.read(cardPhotoStream);
					if (src == null) {
						this.setReturnCode(request,
								IReturnCodeHolder.CARDPHOTO_FORMAT_ERROR,
								MODIFY_ACCOUNT);
						return mapping.findForward(FAILURE);
					}
					cardPhotoStream.close();
					cardPhotoStream = formFile.getInputStream();
				}
			}
		}

		// getMySpaceService().updateAccount(account);
		getMySpaceService().saveOrUpdateAccount(account, photoStream,
				cardPhotoStream);

		// setAcctHis(account,acctHis);
		// getMySpaceService().saveAcctHis(acctHis);
		return mapping.findForward("accountUserInfo");
	}

	// email锟睫革拷
	public ActionForward modifyMail(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		MailActionForm theform = (MailActionForm) form;
		Account account = getAccount(request);
		theform.setEmail(account.getEmail());
		return mapping.findForward("modifyMail");
	}

	// email锟睫革拷锟结交
	public ActionForward modifyMailSubmit(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		MailActionForm theform = (MailActionForm) form;
		Account account = getAccount(request);
		account.setEmail(theform.getEmail());
		account.setUpdateUser(getAccountId(request));
		account.setUpdateTime(new Date());
		log.debug("email1==" + account.getEmail());
		getMySpaceService().updateAccount(account);
		log.debug("email2==" + getAccount(request).getEmail());
		getMySpaceService().sendRegisterActivate(account.getId() + "");
		return mapping.findForward("success");
	}

	// 锟睫改碉拷陆锟斤拷锟斤拷
	public ActionForward modifyLoginPass(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		return mapping.findForward("modifyLoginPass");
	}

	public ActionForward modifyLoginPassSubmit(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {

		ModifyLoginPassForm theForm = (ModifyLoginPassForm) form;
		Account account = getAccount(request);
		if (account.getLoginPassword() == null
				|| account.getLoginPassword().equals(
						SecurityUtil.encryptoMD5String(theForm.getPass()))) {// ????????????????????
			account.setLoginPassword(SecurityUtil.encryptoMD5String(theForm
					.getNewPass()));
			getMySpaceService().updateAccount(account);

			return mapping.findForward("success");
		} else {// 锟斤拷锟斤拷锟诫不匹锟斤拷
			// 锟斤拷哟锟斤拷锟斤拷锟绞?
			return mapping.findForward("modifyLoginPass");
		}

	}

	// 锟睫革拷支锟斤拷锟斤拷锟斤拷
	public ActionForward modifyPayPass(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		return mapping.findForward("modifyPayPass");
	}

	// 锟剿伙拷锟斤拷锟斤拷
	public ActionForward accountList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		log.debug("is runging");
		String accountID = getAccountId(request);
		// DisplayBean displayBean = ics.getDisplayName(accountID);
		String type = request.getParameter("modifyType");
		List aBankList = null;
		if (accountID != null) {
			aBankList = getMySpaceService().getAccountBankList(accountID);
		}
		if (type != null)
			request.getSession().setAttribute("contextType", type);
		request.setAttribute("displayBean", ics.getDisplayName(accountID));
		request.setAttribute("aBankList", aBankList);
		return mapping.findForward("accountList");

	}

	public ActionForward accountDetail(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		String accountID = getAccountId(request);
		String aBankID = request.getParameter("aBankID");
		MyAccountBankForm theForm = (MyAccountBankForm) form;
		request.setAttribute("displayBean", ics.getDisplayName(accountID));
		AccountBank aBank = getMySpaceService().getAccountBank(aBankID);
		// REMARK : MODIFY BY WUBO 20080916
		if (aBank == null
				|| !aBank.getAccount().getId().toString().equals(accountID))
			aBank = null;
		if (aBank != null) {
			BeanUtils.copyProperties(theForm, aBank);
			theForm.setBankInfoId(aBank.getBankInfo().getId() + "");
		}
		request.setAttribute("aBank", aBank);
		List provinceList = (List) InitForString.dataDictMap
				.get("PROVINCE_INFO");
		request.setAttribute("province", provinceList);
		List cityList = null;
		if (theForm.getProvSeq() != null) {
			cityList = (List) InitForString.dataDictMap.get(theForm
					.getProvSeq().toString());
			request.setAttribute("city", cityList);
		} else {
			cityList = (List) InitForString.dataDictMap
					.get(((CityInfo) provinceList.get(0)).getCityId());
			request.setAttribute("city", cityList);
		}
		if (cityList == null) {
			cityList = (List) InitForString.dataDictMap
					.get(((CityInfo) provinceList.get(0)).getCityId());
			request.setAttribute("city", cityList);
		}
		Account account = ics.getAccount(accountID);
		String idcardStatus = getAuthenticateService()
				.getIdcardAuthenticationStatus(account);
		request.setAttribute("idcardStatus", idcardStatus == null ? ""
				: idcardStatus);
		saveToken(request);
		return mapping.findForward("accountDetail");
	}

	public ActionForward accountSubmit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		HttpSession session = request.getSession();
		TransactionTemplate tt = (TransactionTemplate) IPBAppFactory
				.getObj("transactionTemplate");
		AccountSummary as = (AccountSummary) session
				.getAttribute(Constant.SESSION_ACCOUNT_SUMMARY);
		DefaultUserSummary user = (DefaultUserSummary) as.getUser();
		String username = request.getParameter("accountName");
		HibernateAccountDAO hd = null;
		try {
			hd = (HibernateAccountDAO) IPBAppFactory.getObj("accountDAO");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// hd.updateUsername(user, username);
		MyAccountBankForm theForm = (MyAccountBankForm) form;
		Account account = getAccount(request);
		BankInfo bi = getMySpaceService().getBankInfo(theForm.getBankInfoId());

		AccountBank ab = null;
		IMySpaceService mssi = (IMySpaceService) getMySpaceService();

		if (theForm.getId() == null || theForm.getId().length() == 0) {

			ab = new AccountBank();
			BeanUtils.copyProperties(ab, theForm);

			// 检查银行卡号码和别名是否唯一
			if (mssi.isUniqueAccountBank(ab.getAccountId(), account.getId(),
					null)
					&& mssi.isUniqueAccountAlias(ab.getBankAlias(), account
							.getId(), null)) {
				ab.setId(null);
				ab.setIsValid("Y");
				ab.setCreateUser(getAccountId(request));
				ab.setCreateTime(new Date());
				ab.setUpdateUser(getAccountId(request));
				ab.setUpdateTime(new Date());
				ab.setAccountName(username);

				if (account.getAccountBanks().size() == 0) {
					ab.setDefaultFlag("Y");
				} else {
					boolean flag = false;
					Set accountBanks = account.getAccountBanks();
					for (Iterator it = accountBanks.iterator(); it.hasNext();) {
						AccountBank tempAb = (AccountBank) it.next();
						if ("Y".equals(tempAb.getIsValid())
								&& "Y".equals(tempAb.getDefaultFlag())) {// 有默认并且没有删除
							flag = true;
						}
					}
					if (flag) {
						ab.setDefaultFlag("N");
					} else {
						ab.setDefaultFlag("Y");
					}
				}
			} else {
				this.setReturnCode(request,
						IReturnCodeHolder.ACCOUNT_BANK_DUPLICATED,
						ADD_ACCOUNT_BANK);
				return mapping.findForward(FAILURE);
			}
		} else {
			ab = getMySpaceService().getAccountBank(theForm.getId());
			
			// 检查记录是否为当前登录用户的绑定记录
			if(!ab.getAccount().getId().equals(new Long(getAccountId(request)))) {
				// 非当前用户记录，抛出异常
				return mapping.findForward(FAILURE);
			}

			// 检查银行卡号码和别名是否唯一
			if (mssi.isUniqueAccountBank(theForm.getAccountId(), account
					.getId(), ab.getId())
					&& mssi.isUniqueAccountAlias(theForm.getBankAlias(),
							account.getId(), ab.getId())) {
				BeanUtils.copyProperties(ab, theForm);
				ab.setUpdateUser(getAccountId(request));
				ab.setUpdateTime(new Date());
			} else {
				this.setReturnCode(request,
						IReturnCodeHolder.ACCOUNT_BANK_DUPLICATED,
						MODIFY_ACCOUNT_BANK);
				return mapping.findForward(FAILURE);
			}
		}

		ab.setBankInfo(bi);
		ab.setAccount(account);
		ab.setAccountName(account.getName());

		if (isTokenValid(request, true)) {
			mssi.updateAccountBank(ab);
			BankCardMail mail = (BankCardMail) IPBAppFactory.getObj("bankCard");
			mail.setAb(ab);
			String oldSmsContext = mail.getSmsContext();
			if (StringUtil.isStrEmpty(theForm.getId())) {
				mail.setEmailTitle("您的银行账户绑定新增");
				mail.setContentTitle("您的银行账户绑定新增");
				mail.setTitlemessage("您新增了一个绑定银行账户");
			} else {
				mail.setEmailTitle("您的银行账户绑定修改");
				mail.setContentTitle("您的银行账户绑定修改");
				mail.setTitlemessage("您修改了一个已经绑定的银行账户");
				int p = oldSmsContext.indexOf(".vm");
				mail.setSmsContext(oldSmsContext.substring(0, p) + "Modify.vm");
			}
			if (tt.ifSendMail(ab.getAccount(), Constant.BANKCARD))
				mail.sendMail(null, null);
			if (tt.ifSendMobile(ab.getAccount(), Constant.BANKCARD))
				mail.sendSms(null, null);
			mail.setSmsContext(oldSmsContext);

			ab.setAccount(account);
			resetToken(request);
			return mapping.findForward("accountList");
		} else {
			saveToken(request);
			return mapping.findForward("accountList");
		}
	}

	public ActionForward accountDelSubmit(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		String aBankID = request.getParameter("aBankID");
		if (aBankID != null)
			getMySpaceService().delAccountBank(aBankID);
		return mapping.findForward("accountList");

	}

	public ActionForward accountSetDefault(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		String aBankID = request.getParameter("aBankID");
		if (aBankID != null)
			getMySpaceService().updateBankSetDefault(aBankID);

		return mapping.findForward("myspacecontent");

	}

	public ActionForward accountSetDefaultsSpace(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		String aBankID = request.getParameter("aBankID");
		if (aBankID != null)
			getMySpaceService().updateBankSetDefault(aBankID);
		return mapping.findForward("accountList");

	}

	public ActionForward addOperatorPre(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return mapping.findForward("addOperatorPre");
	}

	/***************************************************************************
	 * 跳转到IVR设置页面
	 **************************************************************************/
	public ActionForward newIVR(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		IVRPassForm iform = (IVRPassForm) form;
		iform.setErrorMsg("");
		iform.setPass(null);

		Account account = initAccount(request);
		SubAccount defaultSA = account.getDefaultSubAccount();
		List subAccounts = new ArrayList();
		subAccounts.add(defaultSA);
		Set s = account.getSubAccounts();
		Iterator it = s.iterator();
		while (it.hasNext()) {
			SubAccount subAccount = (SubAccount) it.next();
			if (subAccount.getId().longValue() != account
					.getDefaultSubAccount().getId().longValue()) {
				subAccounts.add(subAccount);
			}
		}
		request.setAttribute("account", account);
		request.setAttribute("subList", subAccounts);
		return mapping.findForward("access");
	}

	/***************************************************************************
	 * IVR设置提交
	 **************************************************************************/
	public ActionForward newIVRSubmit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		IVRPassForm iform = (IVRPassForm) form;
		iform.setIsOpen(request.getParameter("isOpen"));
		HttpSession session = request.getSession();
		AccountSummary user = (AccountSummary) session
				.getAttribute(Constant.SESSION_ACCOUNT_SUMMARY);
		Account account = getMySpaceService().getAccount(
				user.getAccountId() + "");
		String logPass = SecurityUtil.encryptoMD5String(iform.getModNewPass());
		String modPass = SecurityUtil.encryptoMD5String(iform.getLogNewPass());

		if (iform.getPass() != null) {
			String pass = SecurityUtil.encryptoMD5String(iform.getPass());
			if (!pass.equals(account.getPayPassword())) {
				iform.setErrorMsg("您输入的支付密码有误，请重新输入");
				List subList = user.getSubAccountList();
				request.setAttribute("subList", subList);
				request.setAttribute("account", account);
				return mapping.findForward("failed");
			}
		}
		if (iform.isOpen.equals("Y")) {
			account.setIvrStatus(iform.getIsOpen());
			if (iform.getLogNewPass() != null)
				account.setIvrPayPassword(logPass);
			if (iform.getModNewPass() != null)
				account.setIvrLoginPassword(modPass);
			WeatherUtil.fillUpdateInfo(account, account.getId().toString());// 更新最后人员和日期
			getMySpaceService().updateAccount(account);
			List subList = user.getSubAccountList();
			Iterator it = subList.iterator();
			while (it.hasNext()) {
				SubAccount sub = (SubAccount) it.next();

				if (sub.getIvrFlag().equals("Y")) {
					sub.setIvrFlag("N");
					getMySpaceService().updateSubAccount(sub);
				}
				if ((sub.getId().toString()).equals(iform.getSubId())) {
					sub.setIvrFlag("Y");
					getMySpaceService().updateSubAccount(sub);
				}
			}
			return mapping.findForward("access");
		} else {
			account.setIvrLoginPassword("");
			account.setIvrPayPassword("");
			account.setIvrStatus("N");
			WeatherUtil.fillUpdateInfo(account, account.getId().toString());// 更新最后人员和日期
			getMySpaceService().updateAccount(account);
			List subList = user.getSubAccountList();
			Iterator it = subList.iterator();
			while (it.hasNext()) {
				SubAccount sub = (SubAccount) it.next();
				if (sub.getIvrFlag().equals("Y")) {
					sub.setIvrFlag("N");
					getMySpaceService().updateSubAccount(sub);
				}
			}
			return mapping.findForward("access");
		}
	}

	/***************************************************************************
	 * 跳转到IVR修改密码页面
	 **************************************************************************/
	public ActionForward toIVRPass_modify(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		IVRPassForm mform = (IVRPassForm) form;
		mform.setErrorMsg("");
		return mapping.findForward("access");
	}

	/***************************************************************************
	 * IVR修改密码
	 **************************************************************************/
	public ActionForward IVRPass_modify(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		IVRPassForm mform = (IVRPassForm) form;
		Account account = getAccount(request);

		String pass = SecurityUtil.encryptoMD5String(mform.getPass());
		String newPass = SecurityUtil.encryptoMD5String(mform.getNewPass());
		if (mform.modifyType.equals("login")) {
			if (pass.equals(account.getIvrLoginPassword())) {
				account.setIvrLoginPassword(newPass);
				getMySpaceService().updateAccount(account);
			} else {
				// mform.setErrorMsg("您输入的密码有误");
				// return mapping.findForward("failed");

				this.setReturnCode(request,
						IReturnCodeHolder.OLD_PASSWORD_ERROR,
						MODIFY_LOGIN_PASSWORD);
				return mapping.findForward(FAILURE);
			}
		} else {
			if (pass.equals(account.getIvrPayPassword())) {
				account.setIvrPayPassword(newPass);
				getMySpaceService().updateAccount(account);
			} else {
				/*
				 * mform.setErrorMsg("您输入的密码有误"); return
				 * mapping.findForward("failed");
				 */
				this.setReturnCode(request,
						IReturnCodeHolder.OLD_PASSWORD_ERROR,
						MODIFY_PAY_PASSWORD);
				return mapping.findForward(FAILURE);
			}
		}

		return mapping.findForward("access");
	}

	/**
	 * 转到重置操作员登录/支付密码页面（登录用户是企业admin） form里必须已设置modifyType和objectId
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward toResetOperPassword(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		AccountSummary accountsummary = WeatherUtil
				.getLoingInfoFromSession(request);

		ModifyLoginPassForm theForm = (ModifyLoginPassForm) form;
		theForm.setResetFlag(1);
		if (accountsummary.getUserType().equals(USERTYPE_CORP_ADMIN)) {
			// 当前登录用户是企业admin，可重置各操作员的登录密码和支付密码，modifyType和objectId的值在request中传入
			theForm.setObjectType(OBJECT_TYPE_OPERATOR);
		} else {
			// 其他用户没有权限访问这个链接，转到失败页面
			if (theForm.getModifyType().equals(MODIFY_TYPE_PAY)) {
				this.setReturnCode(request,
						IReturnCodeHolder.NO_RIGHT_RESET_PASSWORD,
						RESET_PAY_PASSWORD);
			} else {
				this.setReturnCode(request,
						IReturnCodeHolder.NO_RIGHT_RESET_PASSWORD,
						RESET_LOGIN_PASSWORD);
			}
			return mapping.findForward(FAILURE);
		}

		return mapping.findForward(SUCCESS);
	}

	/**
	 * 转到修改登录/支付密码页面 form里必须已设置modifyType
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward toModifyPassword(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		AccountSummary accountsummary = WeatherUtil
				.getLoingInfoFromSession(request);

		ModifyLoginPassForm theForm = (ModifyLoginPassForm) form;
		theForm.setResetFlag(0);
		if (accountsummary.getUserType().equals(USERTYPE_CORP_OPERATOR)) {
			// 当前用户是企业操作员
			theForm.setObjectType(OBJECT_TYPE_OPERATOR);
			theForm.setObjectId(String
					.valueOf(accountsummary.getOperatorCode()));
		} else if (accountsummary.getUserType().equals(USERTYPE_CORP_ADMIN)) {
			// 当前用户是企业admin
			if (theForm.getModifyType().equals(MODIFY_TYPE_PAY)) {
				// 企业admin没有支付密码，返回到出错页
				this.setReturnCode(request, IReturnCodeHolder.NO_PAY_PASSWORD,
						MODIFY_PAY_PASSWORD);
				return mapping.findForward(FAILURE);
			} else {
				theForm.setObjectType(OBJECT_TYPE_USER);
			}
		} else {
			// 当前用户是个人
			theForm.setObjectType(OBJECT_TYPE_USER);
		}
		return mapping.findForward(SUCCESS);
	}

	/**
	 * 修改密码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward modifyPassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {

		ModifyLoginPassForm theForm = (ModifyLoginPassForm) form;
		String objectType = theForm.getObjectType();
		String objectId = theForm.getObjectId();
		String modifyType = theForm.getModifyType();
		
		
		HttpSession session = request.getSession();
		String mcrypt_key_1=(String)session.getAttribute("mcrypt_key");
		session.removeAttribute("mcrypt_key");//清除session
		
		// 原密码并解密
		String pass = theForm.getPass(); 
		String pass1=AESWithJCE.getResult(mcrypt_key_1,pass);
		
		//取得新密码并解密
		String newpass = theForm.getNewPass(); 
		String newpass1=AESWithJCE.getResult(mcrypt_key_1,newpass);
		
		AccountSummary accountsummary = WeatherUtil
				.getLoingInfoFromSession(request);
		Long operatorCode = accountsummary.getOperatorCode();
		if (operatorCode != null
				&& !objectId.equals(String.valueOf(operatorCode))) {
			this.setReturnCode(request, IReturnCodeHolder.GET_OPERATOR_ERROR,
					MODIFY_PASSWORD);
			return mapping.findForward(FAILURE);
		}
		String password = "";
		if (OBJECT_TYPE_USER.equals(objectType)) { // 如果对象类型是用户(个人或企业admin)
			// 取得当前登录用户
			Account account = getAccount(request);
			if (MODIFY_TYPE_LOGIN.equals(modifyType)) { // 如果修改类型是登录
				if (theForm.getResetFlag() == 1) { // 不需要校验旧密码
					account.setLoginPassword(SecurityUtil
							.encryptoMD5String(newpass1));
				} else { // 需要校验旧密码
					password = account.getLoginPassword();
					if (password.equals(SecurityUtil.encryptoMD5String(pass1))) {
						if (SecurityUtil
								.encryptoMD5String(newpass1).equals(account.getPayPassword())) {
							this.setReturnCode(request,
									IReturnCodeHolder.PAY_LOGIN_ERROR,
									MODIFY_LOGIN_PASSWORD);
							return mapping.findForward(FAILURE);
						}
						account.setLoginPassword(SecurityUtil
								.encryptoMD5String(newpass1));
					} else {
						// 旧密码错误，转到出错页
						this.setReturnCode(request,
								IReturnCodeHolder.OLD_PASSWORD_ERROR,
								MODIFY_LOGIN_PASSWORD);
						return mapping.findForward(FAILURE);
					}
				}
			} else if (MODIFY_TYPE_PAY.equals(modifyType)) { // 如果修改类型是支付
				if (Constant.ACCOUNT_TYPE_BUYER
						.equals(account.getAccountType())) {// 当前登录用户是个人
					if (theForm.getResetFlag() == 1) {// 不需要校验旧密码
						account.setPayPassword(SecurityUtil
								.encryptoMD5String(newpass1));
					} else {// 需要校验旧密码
						password = account.getPayPassword();
						if (password.equals(SecurityUtil
								.encryptoMD5String(pass1))) {
							if (SecurityUtil
								.encryptoMD5String(newpass1).equals(account.getLoginPassword())) {
								this.setReturnCode(request,
										IReturnCodeHolder.PAY_LOGIN_ERROR,
										MODIFY_PAY_PASSWORD);
								return mapping.findForward(FAILURE);
							}
							account.setPayPassword(SecurityUtil
									.encryptoMD5String(newpass1));
						} else {
							// 旧密码错误，转到出错页
							this.setReturnCode(request,
									IReturnCodeHolder.OLD_PASSWORD_ERROR,
									MODIFY_PAY_PASSWORD);
							return mapping.findForward(FAILURE);
						}
					}
				} else {// 当前登录用户是企业admin
					if (theForm.getResetFlag() == 1) {
						this.setReturnCode(request,
								IReturnCodeHolder.NO_PAY_PASSWORD,
								RESET_PAY_PASSWORD);
					} else {
						this.setReturnCode(request,
								IReturnCodeHolder.NO_PAY_PASSWORD,
								MODIFY_PAY_PASSWORD);
					}
					return mapping.findForward(FAILURE);
				}
			}

			// 更新用户（个人或企业admin）
			WeatherUtil.fillUpdateInfo(account, account.getId().toString());// 更新最后人员和日期
			getMySpaceService().updateAccount(account);
			return mapping.findForward(SUCCESS);

		} else if (OBJECT_TYPE_OPERATOR.equals(objectType)) { // 如果对象类型是操作员
			// 根据操作员id得到操作员
			Operator oper = getMySpaceService().getOperatorById(objectId);
			if (MODIFY_TYPE_LOGIN.equals(modifyType)) { // 如果修改类型是登录
				if (theForm.getResetFlag() == 1) { // 不需要校验旧密码
					oper.setLoginPassword(SecurityUtil
							.encryptoMD5String(newpass1));
				} else { // 需要校验旧密码
					
					password = oper.getLoginPassword();
					if (password.equals(SecurityUtil.encryptoMD5String(pass1))) {
						if (SecurityUtil
								.encryptoMD5String(newpass1).equals(oper.getPayPassword())) {
							this.setReturnCode(request,
									IReturnCodeHolder.PAY_LOGIN_ERROR,
									MODIFY_LOGIN_PASSWORD);
							return mapping.findForward(FAILURE);
						}
						oper.setLoginPassword(SecurityUtil
								.encryptoMD5String(newpass1));
					} else {
						// 旧密码错误，转到出错页
						this.setReturnCode(request,
								IReturnCodeHolder.OLD_PASSWORD_ERROR,
								MODIFY_LOGIN_PASSWORD);
						return mapping.findForward(FAILURE);
					}
				}
			} else if (MODIFY_TYPE_PAY.equals(modifyType)) { // 如果修改类型是支付
				if (theForm.getResetFlag() == 1) { // 不需要校验旧密码
					oper.setPayPassword(SecurityUtil.encryptoMD5String(newpass1));
				} else { // 需要校验旧密码
					password = oper.getPayPassword();
					if (password.equals(SecurityUtil.encryptoMD5String(pass1))) {
						oper.setPayPassword(SecurityUtil
								.encryptoMD5String(newpass1));
						if (SecurityUtil.encryptoMD5String(newpass1).equals(oper.getLoginPassword())) {
							this.setReturnCode(request,
									IReturnCodeHolder.PAY_LOGIN_ERROR,
									MODIFY_PAY_PASSWORD);
							return mapping.findForward(FAILURE);
						}
					} else {
						// 旧密码错误，转到出错页
						this.setReturnCode(request,
								IReturnCodeHolder.OLD_PASSWORD_ERROR,
								MODIFY_PAY_PASSWORD);
						return mapping.findForward(FAILURE);
					}
				}
			}

			// 更新操作员
			getMySpaceService().updateOperator(oper);

			if (theForm.getResetFlag() == 1) {
				// 企业admin重置操作员密码
				return mapping.findForward("resetOperPassSuccess");
			} else {
				// 企业操作员修改自己的登录密码或支付密码
				return mapping.findForward(SUCCESS);
			}

		} else { // 即不是用户(个人或企业admin)也不是操作员
			return mapping.findForward(FAILURE);
		}
	}

	public ActionForward subBalance(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {

		Account account = getAccount(request);

		request.setAttribute("account", account);
		total(account, request);

		return mapping.findForward("subBalance");
	}

	/***************************************************************************
	 * 客户升级
	 **************************************************************************/
	public ActionForward upGrading(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		// if(!isTokenValid(request)){
		// return mapping.findForward("access");
		// }
		Account account = getAccount(request);
		// String groupId = getMySpaceService().getGroupByAccount(account,
		// Constant.GROUP_TYPE_C).getId().toString();
		GradeRules gr = getMySpaceService().getGradingRulesByGrading(account);
		IScoresService ss = ScoresFactory.getScoresService();
		String method = gr.getGradingMethod();
		String warning = new String();
		boolean access = false;
		if (method.equals(Constant.BYAUTHENTICATING)) {
			List list = getMySpaceService().getAuthenticationById(
					gr.getId().toString());

			List must = new ArrayList();
			List notMust = new ArrayList();

			getMySpaceService().setList(list, must, notMust);
			must = getMySpaceService().authenticat(must, account);
			notMust = getMySpaceService().authenticat(notMust, account);

			Iterator it = must.iterator();
			boolean typeaccess = true;
			StringBuffer warn = new StringBuffer("您没有通过");
			if (must.size() == 0) {
				access = true;
			} else {
				while (it.hasNext()) {
					AuthenticationBean bean = (AuthenticationBean) it.next();
					if (!bean.getIfAccess().equals("Y")) {
						warn.append("A类认证");
						typeaccess = false;
						// return mapping.findForward("failed");
					}
				}
			}
			if (notMust.size() == 0) {
				access = true;
			} else {
				it = notMust.iterator();
				while (it.hasNext()) {
					AuthenticationBean bean = (AuthenticationBean) it.next();
					if (bean.getIfAccess().endsWith("Y")) {
						access = true;
						break;
					}
				}
			}
			if (!access) {
				typeaccess = false;

				warn.append("B类认证");
				// request.setAttribute("warning", warning);
				// return mapping.findForward("failed");
			}
			if (!typeaccess) {
				warning = warn.toString();
				request.setAttribute("warning", warning);
				return mapping.findForward("failed");
			}
		}

		if (method.equals(Constant.BYSCORES)) {
			if (account.getTotalScores().doubleValue() < gr.getScoresAmount()
					.doubleValue()) {
				warning = "您的积分不够";
				request.setAttribute("warning", warning);
				return mapping.findForward("failed");
			}
			String success = ss
					.calcScores(account, new Double(gr.getAdjusteScore()
							.doubleValue()), Constant.SCORES_SOURCE_J);// 客户升级积分
			if (success.equals(Constant.DEDUCE_SCORES_B)) {
				warning = "您的积分不够";
				request.setAttribute("warning", warning);
				return mapping.findForward("failed");
			}
			if (success.equals(Constant.DEDUCE_SCORES_C)) {
				warning = "您的积分没有激活，请在账户首页激活您的积分";
				request.setAttribute("warning", warning);
				return mapping.findForward("failed");
			}
		}
		account.setAccountGroupses(getMySpaceService().getAccountGroupsSet(
				account, Constant.GROUP_TYPE_C, gr.getGroupsByNextGrading()));
		WeatherUtil.fillUpdateInfo(account, account.getId().toString());
		getMySpaceService().updateAccount(account);
		request.setAttribute("grading", gr.getGroupsByNextGrading().getName());

		// resetToken(request);
		return mapping.findForward("access");
	}

	public ActionForward toUpGrading(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		request.setAttribute("warning", request.getAttribute("warning"));
		Account account = getAccount(request);
		GradeRules gr = getMySpaceService().getGradingRulesByGrading(account);

		List list = getMySpaceService().getAuthenticationById(
				gr.getId().toString());
		List message = new ArrayList();
		List mustMessage = new ArrayList();

		String warn = new String();
		if (gr.getGradingMethod().equals(Constant.BYSCORES)) {
			warn = "您需要" + gr.getScoresAmount().toString() + "的积分以升级为"
					+ gr.getGroupsByNextGrading().getName()
					+ "，您将需要扣除相应的积分以完成升级";
			message.add(warn);
		}
		if (gr.getGradingMethod().equals(Constant.BYAUTHENTICATING)) {
			getMySpaceService().setList(list, mustMessage, message);
			getMySpaceService().ifAccess(request, account);
			message = getMySpaceService().authenticat(message, account);
		}

		mustMessage = getMySpaceService().authenticat(mustMessage, account);
		request.setAttribute("warn", message);
		request.setAttribute("mustMessage", mustMessage);
		request.setAttribute("grading", gr);
		// saveToken(request);
		return mapping.findForward("access");

	}

	public ActionForward testBank(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		Account account = getAccount(request);
		String warning = new String();
		if (getAuthenticateService().feasibleBankCardAuthentication(account)) {
			warning = "您的银行卡成功验证";
			getAuthenticateService().setBankCardAuthenticationStatus(account,
					Constant.AUTHENTICATION_STATUS_PASS);
		} else {
			warning = "您的银行卡未能通过验证，您需要使用您的银行卡进行充值或者提现交易，再申请验证";
			getAuthenticateService().setBankCardAuthenticationStatus(account,
					Constant.AUTHENTICATION_STATUS_UNPASS);

		}
		request.setAttribute("warning", warning);
		return mapping.findForward("access");
	}

	public void total(Account account, HttpServletRequest request) {

		double num = 0.00;
		double num1 = 0.00;
		Double balance;
		Double lockAmount;
		Set set = new HashSet();
		set = account.getSubAccounts();
		Iterator iter = set.iterator();
		while (iter.hasNext()) {
			SubAccount sa = (SubAccount) iter.next();
			if (sa.getAccountBalance() != null) {
				balance = (sa.getAccountBalance().getBalance());
				lockAmount = (sa.getAccountBalance().getLockAmount());
				num = num + balance.doubleValue();
				if (lockAmount == null) {
					num1 = num1 + 0.00;
				} else {
					num1 = num1 + lockAmount.doubleValue();
				}
			}
		}
		try {
			GradeRules gr = getMySpaceService().getGradingRulesByGrading(
					account);
			request.setAttribute("grading", gr);
			String accountID = getAccountId(request);
			List aBankList = null;
			if (accountID != null) {
				aBankList = getMySpaceService().getAccountBankList(accountID);
			}
			request.setAttribute("displayBean", ics.getDisplayName(accountID));
			request.setAttribute("totalbank", aBankList.size());
			request.setAttribute("aBankList", aBankList);

		} catch (IPBException e) {
			e.printStackTrace();
		}

		request.setAttribute("sumBalance", new Double(num));
		request.setAttribute("sumAmount", new Double(num1));
	}

	public void setAcctHis(Account acct, AccountHis acctHis) {
		acctHis.setAccountId(acct.getAccountId());
		acctHis.setAccountType(acct.getAccountType());
		acctHis.setActiveCode(acct.getActiveCode());
		acctHis.setAddr(acct.getAddr());
		acctHis.setAnswer(acct.getAnswer());
		acctHis.setCitySeq(acct.getCitySeq());
		acctHis.setCreateTime(acct.getCreateTime());
		acctHis.setCreateUser(acct.getCreateUser());
		acctHis.setEmail(acct.getEmail());
		acctHis.setFlag(acct.getFlag());
		acctHis.setIdCode(acct.getIdCode());
		acctHis.setIdType(acct.getIdType());
		acctHis.setLoginPassword(acct.getLoginPassword());
		acctHis.setMobile(acct.getMobile());
		acctHis.setName(acct.getName());
		acctHis.setOfferPerson(acct.getOfferPerson());
		acctHis.setPayPassword(acct.getPayPassword());
		// acctHis.setPhoto(acct.getPhoto());
		acctHis.setProvSeq(acct.getProvSeq());
		acctHis.setQuestion(acct.getQuestion());
		acctHis.setRemark(acct.getRemark());
		acctHis.setStatus(acct.getStatus());
		acctHis.setTel(acct.getTel());
		acctHis.setUpdateTime(acct.getUpdateTime());
		acctHis.setUpdateUser(acct.getUpdateUser());
		// acctHis.setVersion(acct.getVersion());
		acctHis.setZipCode(acct.getZipCode());
		acctHis.setCardPhoto(null);
		acctHis.setPhoto(null);
		acctHis.setCardPhotoBack(null);
		acctHis.setTempCardPhoto(null);
		acctHis.setTempCardPhotoBack(null);
	}

	public ActionForward preModifyCryptoKey(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		return mapping.findForward("success");
	}

	public ActionForward modifyCryptoKey(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		long accountId = WeatherUtil.getLoingInfoFromSession(request)
				.getAccountId();
		Account account = getMySpaceService().getAccount(
				String.valueOf(accountId));
		String cryptoKey = account.getKey();
		
		HttpSession session = request.getSession();
		String mcrypt_key_1=(String)session.getAttribute("mcrypt_key");//获取session中随机因子
		session.removeAttribute("mcrypt_key");//清除session

		String password1 = request.getParameter("oldCryptoKey"); // 原密码
		String oldCryptoKey=AESWithJCE.getResult(mcrypt_key_1,password1);//解密后原密钥
		
		StringUtil.isStrEmpty(cryptoKey);
		if (cryptoKey != null && cryptoKey.length() > 0
				&& !cryptoKey.equals(oldCryptoKey)) {
			request.setAttribute("message", "原密钥错误！");
			return mapping.findForward("failure");
		}
		String password2 = request.getParameter("newCryptoKey"); // 新密钥
		String newCryptoKey=AESWithJCE.getResult(mcrypt_key_1,password2);//解密后新密钥
		
		account.setKey(newCryptoKey == null ? "" : newCryptoKey.trim());
		WeatherUtil.fillUpdateInfo(account, account.getId().toString());// 更新最后人员和日期
		getMySpaceService().updateAccount(account);
		return mapping.findForward("success");
	}

	private Account initAccount(HttpServletRequest request) throws IPBException {
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		AccountTemplateInter at = (AccountTemplateInter) IPBMgrFactory
				.getMgr("accountTemplate");
		Account account = at.getAccount(String.valueOf(accountId));
		// request.setAttribute("subAccounts",acco.getSubAccounts());
		return account;
	}

	// 发送重置密码确认码的邮件
	private void sendResetPwdCodeMail(HttpServletRequest request,
			String vericode, String resetPwdType) throws IPBException,
			Exception {
		SysSet setService = (SysSet) IPBAppFactory.getObj("sysSet");
		if (setService.getCheckVericode()) {
			this.checkVericode(request, vericode);
		}

		String email = getAccount(request).getEmail();
		IAccountService as = (IAccountService) IPBAppFactory
				.getObj("accountService");

		// 修改account，设置resetPwdCode，并发送email，告知用户重置密码的确认码
		as.sendResetPasswordCodeMail(email, resetPwdType);
	}

	// 个人用户通过email申请重置支付密码
	public ActionForward applyResetPayPasswordByEmail(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String vericode = resetForm.getVericode();
		sendResetPwdCodeMail(request, vericode,
				IAccountConst.RESET_PWD_TYPE_PAY);
		return mapping.findForward(SUCCESS);
	}

	// 个人用户通过email申请重置电话账号登录/支付密码
	public ActionForward applyResetIVRPasswordByEmail(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String vericode = resetForm.getVericode();
		if (request.getParameter("modifyType").equals(
				IAccountConst.MODIFY_TYPE_PAY)) {
			sendResetPwdCodeMail(request, vericode,
					IAccountConst.RESET_PWD_TYPE_IVR_PAY);
		} else {
			sendResetPwdCodeMail(request, vericode,
					IAccountConst.RESET_PWD_TYPE_IVR_LOGIN);
		}

		request.setAttribute("modifyType", request.getParameter("modifyType"));
		return mapping.findForward(SUCCESS);
	}

	// 发送重置密码确认码的短信
	private void sendResetPwdCodeSms(HttpServletRequest request,
			String vericode, String resetPwdType) throws IPBException,
			Exception {
		SysSet setService = (SysSet) IPBAppFactory.getObj("sysSet");
		if (setService.getCheckVericode()) {
			this.checkVericode(request, vericode);
		}

		String mobile = getAccount(request).getMobile();
		ServiceFacade sf = (ServiceFacade) IPBAppFactory
				.getObj("serviceFacade");

		// 修改account，设置resetPwdCode，并发送短信，告知用户重置登录密码的确认码
		sf.sendResetPasswordCodeSms(mobile, resetPwdType);
	}

	// 个人用户通过mobile申请重置支付密码
	public ActionForward applyResetPayPasswordByMobile(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String vericode = resetForm.getVericode();
		sendResetPwdCodeSms(request, vericode, IAccountConst.RESET_PWD_TYPE_PAY);
		return mapping.findForward(SUCCESS);
	}

	// 个人用户通过mobile申请重置电话账户登录/支付密码
	public ActionForward applyResetIVRPasswordByMobile(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String vericode = resetForm.getVericode();
		if (request.getParameter("modifyType").equals(
				IAccountConst.MODIFY_TYPE_PAY)) {
			sendResetPwdCodeSms(request, vericode,
					IAccountConst.RESET_PWD_TYPE_IVR_PAY);
		} else {
			sendResetPwdCodeSms(request, vericode,
					IAccountConst.RESET_PWD_TYPE_IVR_LOGIN);
		}

		request.setAttribute("modifyType", request.getParameter("modifyType"));
		return mapping.findForward(SUCCESS);
	}

	// 重置支付密码（登录用户是个人，忘记支付密码，申请重置第二步提交表单）
	public ActionForward resetPayPassword(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		Account ac = getAccount(request);

		ResetPwdForm resetForm = (ResetPwdForm) form;
		String resetCode = resetForm.getResetCode();
		if (resetForm.getEmail() == null) {// 通过mobile
			resetCode = RESET_PWD_TYPE_PAY + ",m," + resetCode;
		} else {// 通过email
			resetCode = RESET_PWD_TYPE_PAY + ",e," + resetCode;
		}

		// 判断当前登录用户是否有权限访问这个页面
		// 如果没有权限，转到失败页面，并告知原因
		if (!ac.getAccountType().equals(Constant.ACCOUNT_TYPE_BUYER)
				|| ac.getResetPwdCode() == null
				|| !ac.getResetPwdCode().equals(resetCode)) {
			this.setReturnCode(request,
					IReturnCodeHolder.NO_RIGHT_RESET_PASSWORD,
					RESET_PAY_PASSWORD);
			return mapping.findForward(FAILURE);
		}

		// 重置支付密码，并将resetPwdCode字段清空
		HttpSession session = request.getSession();
		String mcrypt_key_1 = (String) session.getAttribute("mcrypt_key");// 获取session中随机因子
		String pass = resetForm.getNewPass();
		String newPass=AESWithJCE.getResult(mcrypt_key_1, pass);
		if (SecurityUtil.encryptoMD5String(newPass).equals(ac.getLoginPassword())) {
			this.setReturnCode(request,
					IReturnCodeHolder.PAY_LOGIN_ERROR,
					RESET_PAY_PASSWORD);
			return mapping.findForward(FAILURE);
		}
		ac.setPayPassword(SecurityUtil.encryptoMD5String(newPass));
		ac.setResetPwdCode(null);
		getMySpaceService().updateAccount(ac);

		return mapping.findForward(SUCCESS);
	}

	// 重置电话账户登录/支付密码
	public ActionForward resetIVRPassword(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		Account ac = getCurrentAccount(request);

		ResetPwdForm resetForm = (ResetPwdForm) form;
		String resetCode = resetForm.getResetCode();
		if (resetForm.getEmail() == null) {// 通过mobile
			resetCode = ",m," + resetCode;
		} else {// 通过email
			resetCode = ",e," + resetCode;
		}

		String modifyType = request.getParameter("modifyType");
		if (modifyType.equals(IAccountConst.MODIFY_TYPE_PAY)) {
			resetCode = RESET_PWD_TYPE_IVR_PAY + resetCode;
		} else {
			resetCode = RESET_PWD_TYPE_IVR_LOGIN + resetCode;
		}

		// 判断当前登录用户是否有权限访问这个页面
		// 如果没有权限，转到失败页面，并告知原因
		if (!ac.getAccountType().equals(Constant.ACCOUNT_TYPE_BUYER)
				|| ac.getResetPwdCode() == null
				|| !ac.getResetPwdCode().equals(resetCode)) {
			if (modifyType.equals(IAccountConst.MODIFY_TYPE_PAY)) {
				this.setReturnCode(request,
						IReturnCodeHolder.NO_RIGHT_RESET_PASSWORD,
						RESET_PAY_PASSWORD);
			} else {
				this.setReturnCode(request,
						IReturnCodeHolder.NO_RIGHT_RESET_PASSWORD,
						RESET_LOGIN_PASSWORD);
			}
			return mapping.findForward(FAILURE);
		}

		String pass = resetForm.getNewPass();
		if (modifyType.equals(IAccountConst.MODIFY_TYPE_PAY)) {
			ac.setIvrPayPassword(SecurityUtil.encryptoMD5String(pass));
		} else {
			ac.setIvrLoginPassword(SecurityUtil.encryptoMD5String(pass));
		}
		ac.setResetPwdCode(null);
		getMySpaceService().updateAccount(ac);

		return mapping.findForward(SUCCESS);
	}

	/**
	 * 检验验证码
	 * 
	 * @param request
	 * @param form
	 * @throws BusinessException
	 * @throws MySpaceException
	 */
	public void checkVericode(HttpServletRequest request, String vericode)
			throws MySpaceException {

		String refer = (String) WebUtil.getSessionString(request,
				Constant.SESS_VERICODE);

		if (refer == null) {
			throw MySpaceException.VERIFYCODE_INVALID;
		}
		// 校验码取出一次后就立即更新
		this.refreshVericode(request);

		if (refer == null || !refer.equals(vericode)) {
			// 校验码不正确
			throw MySpaceException.WRONG_VERIFYCODE;
		}
	}

	/**
	 * 重新得到验证码
	 * 
	 * @param request
	 */
	private void refreshVericode(HttpServletRequest request) {
		String vericode = genVericode();
		WebUtil.setSessionString(request, Constant.SESS_VERICODE, vericode);
	}

	/** 按表单存放校验码 */
	public String genVericode() {
		String code = UniqueIdentityUtil.createRandomString(4);
		return code;
	}

	protected final AccountTemplateInter getAccountTemplate() {
		return (AccountTemplateInter) IPBAppFactory
				.getObj(ForeDict.ACCOUNT_TEMPLATE);
	}

	/**
	 * 获取当前账户
	 */
	protected final Account getCurrentAccount(HttpServletRequest request) {
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		return getAccountTemplate().getAccount(String.valueOf(accountId));
	}

}